package com.cuicuisha.gxyp.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.cuicuisha.gxyp.model.entity.system.SysUser;
import com.cuicuisha.gxyp.model.entity.system.SysUserAuthContextUtil;
import com.cuicuisha.gxyp.model.vo.common.Result;
import com.cuicuisha.gxyp.model.vo.common.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: LoginAuthInterceptor
 * Description:
 *
 * @Author 脆脆鲨
 * @Create 2024-09-11 11:34
 * @Version 1.0
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        // 如果是跨域预检请求，直接放行
        if ("OPTIONS".equals(method)) {
            return true;
        }

        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)){
            responseNoLoginInfo(response);
            return false;
        }

        String sysUserInfoJson = redisTemplate.opsForValue().get("user:login:" + token);
        if (StrUtil.isEmpty(sysUserInfoJson)){
            responseNoLoginInfo(response);
            return false;
        }

        // 将用户数据存储到ThreadLocal中,这样在一次请求的中流可以在controller、service、mapper中获取用户数据
        SysUserAuthContextUtil.set(JSON.parseObject(sysUserInfoJson, SysUser.class));
        // 重置Redis中的用户数据的有效时间
        redisTemplate.expire("user:login:" + token, 30, TimeUnit.MINUTES);
        // 放行
        return true;
    }

    private void responseNoLoginInfo(HttpServletResponse response){
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (writer!=null) {writer.close();}
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SysUserAuthContextUtil.remove();
    }

}
